<template>
  <label :for="id">
    <button open-type="getPhoneNumber"
            class="hide"
            :id="id"
            v-if="!phone"
            @getphonenumber="getPhoneNumber"
    >
    </button>
    <button class="hide"
            :id="id"
            v-else
            @click="next"
    >
    </button>
    <slot></slot>
  </label>
</template>

<script>
  import WXAJAX from '@/utils/request'
  import { clearLoginInfo } from '@/utils';
  import { mapGetters, mapActions } from 'vuex';

  export default {
    name: "getPhoneNumber",
    props: {
      eventName: {
        type: String,
        default: 'next',
      }
    },
    data(){
      return {
        id: Date.now()*Math.random(),
        phone: wx.getStorageSync('phone') || '',
      }
    },
    methods:{
      // ...mapActions(['setPhone']),
      next(){
        this.$emit(this.eventName);
      },
      getPhoneNumber(e){
        if (this.phone) return;

        if(!e.target.encryptedData){
          this.next();
          return;
        }

        WXAJAX.POST({
          phoneData:  e.target.encryptedData,
          phoneIv: e.target.iv,
        }, '', '/home/getWxPhone')
          .then(res=>{
            wx.setStorageSync('phone', res);
            // this.setPhone(res);
          }).catch(err=>{
          clearLoginInfo();
        }).finally(()=>{
            this.next(this.eventName);
        });
      },
    },
    computed:{
      ...mapGetters(['selfPhone']),
    }
  }
</script>

<style scoped>
  .reset{
    position: static;
    padding: 0;
    text-align: left;
    line-height: 1;
    border-radius: 0;
    overflow: auto;
  }
  .reset-hover{
    background: transparent;

  }
</style>
